package com.ppl.server.serializers;

import akka.serialization.JSerializer;
import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtostuffIOUtil;
import com.dyuproject.protostuff.Schema;
import com.dyuproject.protostuff.runtime.RuntimeSchema;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created with IntelliJ IDEA.
 * User: Vincent
 * Date: 11/1/12
 * Time: 12:44 PM
 * To change this template use File | Settings | File Templates.
 */
public class ProtostuffRuntimeSerializer extends JSerializer {
  private static final Logger log = LoggerFactory.getLogger(ProtostuffRuntimeSerializer.class);

  static {
    // must enable to support inheritance on non-abstract base types.
    System.setProperty("protostuff.runtime.morph_non_final_pojos", "true");
  }

  @Override
  public Object fromBinaryJava(byte[] bytes, Class<?> aClass) {
    try {
      Schema schema = RuntimeSchema.getSchema(aClass);
      Object loadedObject = aClass.newInstance();

      ProtostuffIOUtil.mergeFrom(bytes, loadedObject, schema);
      return loadedObject;
    } catch (Exception e) {
      log.error("An error has occurred while de-serializing an object", e);
    }

    return null;
  }

  @Override
  public int identifier() {
    return 42;
  }

  @Override
  public byte[] toBinary(Object o) {
    Schema schema = RuntimeSchema.getSchema(o.getClass());
    LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
    return ProtostuffIOUtil.toByteArray(o, schema, buffer);
  }

  @Override
  public boolean includeManifest() {
    return true;
  }
}
